import { isEmpty, isNotEmpty } from './is';
import { HideLoading, Loading, Toast } from './uniapi/prompt';
import { useUserStore } from '@/store/modules/user';
import { Base64 } from 'js-base64';
import { uploadApi } from '@/api/sys/file';
import FileSaver from 'file-saver';

/**
 * 上传文件
 * @param rawFile 文件
 * @param callback 回调
 */
export function uploadFile(rawFile: any, callback?: Function) {
  if (!rawFile) {
    Toast('文件为空');
    return;
  }
  Loading('上传中');
  uploadApi(rawFile)
    .then(({ data }) => {
      HideLoading();
      if (callback) {
        callback(data);
      }
    })
    .catch((e) => {
      console.log(e);
      Toast('上传失败！');
    });
}

/**
 * 下载文件
 * @param url 下载地址
 * @param name 文件名
 */
export function downloadFile(url: string, name?: string) {
  if (isEmpty(url)) {
    Toast('下载链接无效！');
  }
  let fileName = '';
  if (name && isNotEmpty(name)) {
    fileName = name;
  } else {
    fileName = url.substring(url.lastIndexOf('/') + 1);
  }
  const userStore = useUserStore();
  const downloadUrl = url + '?access_token=' + userStore.getToken();
  FileSaver.saveAs(downloadUrl, fileName);
}

/**
 * 浏览附件
 * @param url
 */
export function previewFile(url: string) {
  if (isEmpty(url)) {
    Toast('链接无效！');
  }
  uni.navigateTo({
    url: '/pages/file/file-preview?url=' + encodeURIComponent(Base64.encode(url)),
  });
}
